package com.lbs.jiepiaisi.activity;

import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.allenliu.versionchecklib.core.AllenChecker;
import com.allenliu.versionchecklib.core.VersionParams;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.base.BaseActivityManager;
import com.lbs.jiepiaisi.base.BaseFragmentActivity;
import com.lbs.jiepiaisi.fragment.PhotoFragment;
import com.lbs.jiepiaisi.fragment.PlatformFragment;
import com.lbs.jiepiaisi.fragment.ServiceFragment;
import com.lbs.jiepiaisi.service.DownloadService;
import com.lbs.jiepiaisi.utils.ToastUtil;
import com.lbs.jiepiaisi.utils.UrlUtil;
import com.lbs.jiepiaisi.view.AccountViewPager;

/**
 * Created by yu on 2020-06-29 15:17.
 * Description:
 */

public class OpenFragmentActivity extends BaseFragmentActivity implements View.OnLayoutChangeListener{

    private Fragment[] fragments = {new ServiceFragment(),new PlatformFragment(),new PhotoFragment()};
    private String[] titles = {"服务","平台","拍照"};
    private int[] icons_normal = {R.mipmap.service_normal,R.mipmap.platform_normal,R.mipmap.photo_normal};
    private int[] icons_select = {R.mipmap.service_select,R.mipmap.platform_select,R.mipmap.photo_select};

    private TabLayout tabLayout;
    private AccountViewPager viewPager;

    private View rootView;
    private int keyHeight = 0;

    @Override
    protected void getExtras() {
        setContentView(R.layout.activity_platform_main_fragment);
    }

    @Override
    protected void findView() {


        tabLayout = findViewById(R.id.tablayout);
        viewPager = findViewById(R.id.viewpager);

        rootView = findViewById(R.id.root_vi);
        //阀值设置为屏幕高度的1/3
        keyHeight = this.getWindowManager().getDefaultDisplay().getHeight() / 3;

        viewPager.setOffscreenPageLimit(3);
        viewPager.setAdapter(new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int i) {
                return fragments[i];
            }

            @Override
            public int getCount() {
                return fragments.length;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                return titles[position];
            }
        });


        tabLayout.setupWithViewPager(viewPager);
        //tabLayout.getTabAt(0).select();

//        for (int i = 0; i < titles.length; i++) {
//            if (i == 0) {// 默认选中第一个
//                tabLayout.getTabAt(0).setIcon(icons_select[0]);
//            } else {
//                tabLayout.getTabAt(i).setIcon(icons_normal[i]);
//            }
//        }

        //初始化菜单栏显示
        for (int i = 0; i < tabLayout.getTabCount(); i++) {
            View view = LayoutInflater.from(this).inflate(R.layout.account_tab_item, null);
            TextView mTabText = view.findViewById(R.id.tab_item_text);
            ImageView mTabIcon = view.findViewById(R.id.tab_item_img);
            mTabText.setText(titles[i]);
            mTabIcon.setImageResource(icons_normal[i]);
            if (i == 0) {
                mTabIcon.setImageResource(icons_select[i]);
                mTabText.setTextColor(ContextCompat.getColor(this, R.color.blue));
            }
            tabLayout.getTabAt(i).setCustomView(view);
        }


        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                itemSelect(tab);
                viewPager.setCurrentItem(tab.getPosition());
//                for (int i = 0; i < titles.length; i++) {
//                    if (tab == tabLayout.getTabAt(i)) {
//                        tabLayout.getTabAt(i).setIcon(icons_select[i]);
//                        viewPager.setCurrentItem(i);
//                    }
//                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                itemDeselect(tab);
//                for (int i = 0; i < titles.length; i++) {
//                    if (tab == tabLayout.getTabAt(i)) {
//                        tabLayout.getTabAt(i).setIcon(icons_normal[i]);
//                    }
//                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

//        try{
////            if(isFirst){
//            //检查更新
//            VersionParams.Builder builder = new VersionParams.Builder()
//                    .setRequestUrl(UrlUtil.CHECK_VERSION)
//                    .setForceRedownload(true)
//                    .setShowNotification(true)
//                    .setService(DownloadService.class);
//            //CustomVersionDialogActivity.customVersionDialogIndex = 2;
//            builder.setCustomDownloadActivityClass(DownLoadDialogActivity.class);
//            AllenChecker.startVersionCheck(this, builder.build());
////            }
//        }catch (Exception e){
//
//        }
    }

    //选中，改变其样式
    private void itemSelect(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = customView.findViewById(R.id.tab_item_text);
        ImageView tabIcon = customView.findViewById(R.id.tab_item_img);
        tabText.setTextColor(ContextCompat.getColor(this, R.color.base_color));
        String stitle = tabText.getText().toString();
        for(int i = 0; i < titles.length; i++){
            if(titles[i].equals(stitle)){
                tabIcon.setImageResource(icons_select[i]);
            }
        }
    }
    //非选中，改变其样式
    private void itemDeselect(TabLayout.Tab tab) {
        View customView = tab.getCustomView();
        TextView tabText = customView.findViewById(R.id.tab_item_text);
        ImageView tabIcon = customView.findViewById(R.id.tab_item_img);
        tabText.setTextColor(ContextCompat.getColor(this, R.color.gray_8f));
        String stitle = tabText.getText().toString();
        for(int i = 0; i < titles.length; i++){
            if(titles[i].equals(stitle)){
                tabIcon.setImageResource(icons_normal[i]);
            }
        }
    }

    @Override
    protected void setListener() {

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideKeyboard(v,ev)) {
                v.clearFocus();//清除Edittext的焦点从而让光标消失
                hideKeyboard(v.getWindowToken());
            }
        }

        return super.dispatchTouchEvent(ev);
    }

     private boolean isShouldHideKeyboard(View v, MotionEvent event) {

        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationOnScreen(l);
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getRawX() > left &&event.getRawX() < right && event.getRawY()> top && event.getRawY() < bottom) {//点击EditText的时候不做隐藏处理
                 return false;
            } else {
                return true;
            }
        }
        //如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
         return false;
    }

    private void hideKeyboard(IBinder token) {
        if (token != null) {
            //若token不为空则获取输入法管理器使其隐藏输入法键盘
            InputMethodManager im = (InputMethodManager)getSystemService(mContext.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private long exitTime = 0;
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN){
            if((System.currentTimeMillis() - exitTime) > 2000){
                ToastUtil.show("再按一次退出程序");
                exitTime = System.currentTimeMillis();
            } else {
                BaseActivityManager.getInstance().finishAll();
                //System.exit(0);
                //finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onResume() {
        super.onResume();
        rootView.addOnLayoutChangeListener(this);
    }

    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //Log.e("kkkkkkk","检测键盘 = "+keyHeight+"--"+ (oldBottom - bottom));
        //现在认为只要控件将Activity向上推的高度超过了1/3屏幕高，就认为软键盘弹起
        if(oldBottom != 0 && bottom != 0 &&(oldBottom - bottom > keyHeight)){
            //Log.e("kkkkkkk","关闭弹起！！！");
            //Toast.makeText(OpenFragmentActivity.this, "监听到软键盘弹起...", Toast.LENGTH_SHORT).show();
//            mLinBottom.setVisibility(View.GONE);
//            activityRootView.scrollTo(0,keyHeight + 20);
//            findViewById(R.id.fragment_container).scrollTo(0,-250);
        }else if(oldBottom != 0 && bottom != 0 &&(bottom - oldBottom > keyHeight)){
            //Log.e("kkkkkkk","关闭键盘");
            //Toast.makeText(OpenFragmentActivity.this, "监听到软件盘关闭...", Toast.LENGTH_SHORT).show();
//            mLinBottom.setVisibility(View.VISIBLE);
//            activityRootView.scrollTo(0,0);
            //activityRootView.scrollTo(0,0);
            //activityRootView.scrollTo(0,keyHeight/2);
//            findViewById(R.id.fragment_container).scrollTo(0,0);
        }
    }

}
